package cn.nawang.ebeim.ui.controller;

import java.sql.SQLException;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.nawang.ebeim.client.bean.BackupBean;
import cn.nawang.ebeim.client.bean.DataSource;
import cn.nawang.ebeim.client.bean.RecoveryBean;
import cn.nawang.ebeim.client.util.Constants;
import cn.nawang.ebeim.client.util.DbUtil;
import cn.nawang.ebeim.client.version.Node;
import cn.nawang.ebeim.client.version.VersionTree;
import cn.nawang.ebeim.client.version.VersionTreeUtil;
import cn.nawang.ebeim.ui.bean.DatasourceView;
import cn.nawang.ebeim.ui.bean.User;
import cn.nawang.ebeim.ui.util.ApiUtil;
import cn.nawang.ebeim.ui.util.DatasourceSecurityRankUtil;
import cn.nawang.ebeim.ui.util.UIversionTreeUtil;

/**
 * @ClassName: FileOptController
 * @Description: TODO
 * @author fanyb
 * @date Nov 12, 2015 5:45:01 PM
 * @version v1.0
 */
@RestController
public class FileOptController {
  private static final Logger LOG = LoggerFactory.getLogger(FileOptController.class);
  
  @Autowired
  private HttpSession session;

  /**
   * @author zhangjf
   * @Description: 文件恢复
   * @param @param dsId
   * @param @param path
   * @param @param version
   * @param @param dynamicCode
   * @param @param abDir
   * @param @return
   * @param @throws Exception
   * @return String
   * @date 2015年10月29日上午8:45:05
   *
   * @修改人 zhangjf
   * @修改日期
   */
  @RequestMapping(value = "/recovery", method = RequestMethod.GET)
  public String recoveryFile(String dsId, String path, String version, String dynamicCode,
      String abDir, String nid,String rootTreeDsId) throws Exception {
    LOG.info("recovery .................path abDir before:" + path + "," + abDir);
    path = java.net.URLDecoder.decode(path, "utf-8");
    abDir = java.net.URLDecoder.decode(abDir, "utf-8");
    LOG.info("recovery .................path abDir after:" + path + "," + abDir);

    DatasourceView view = null;
    String ds = ApiUtil.getDataSourceByDsId(dsId);
    JSONObject json = JSONObject.parseObject(ds);
    json.put("dsId", dsId);
    String code = json.getString("code");
    if (code.equals("200")) {
      JSONObject dsjson = json.getJSONObject("obj");
      
      int dsStatus = dsjson.getIntValue("dsStatus");
      String dsVersion = dsjson.getString("currentVersionMajor")+".0";
      if(dsStatus == Constants.DS_STATUS_NOUSE){
        json.put("code", "500");
        json.put("message", "该数据源已停用，请先启用该数据源再进行下载");
        return json.toString();
      }
      view = JSONObject.toJavaObject(dsjson, DatasourceView.class);
      if (view.getStatus() == Constants.DS_RUN_STATUS_RUNNING
          && dsVersion.equals(version)) {
        json.put("code", "500");
        json.put("message", "该数据源正在备份中，请等待备份完成后进行下载");
        return json.toString();
      }

      if(view.getDsType().equals(Constants.DS_TYPE_SAFEBOX)){
        JSONObject check = DatasourceSecurityRankUtil.checkUserRank((User)session.getAttribute("user"), dynamicCode, session);
        if (!check.getString("code").equals("200")) {
          return check.toString();
        }
      }else{
        JSONObject check = DatasourceSecurityRankUtil
            .check(view.getDsSecurityRank(), dynamicCode, session);
        if (!check.getString("code").equals("200")) {
          return check.toString();
        }
      }
    } else {
      json.put("code", "500");
    }
    
    if(rootTreeDsId!=null && rootTreeDsId.length()>0){
      DataSource rootTreeDs = UIversionTreeUtil.getDsByDsId(rootTreeDsId);
      String rootTreeVersion = rootTreeDs.getCurrentVersionMajor()+"."+rootTreeDs.getCurrentVersionMinor();
      VersionTree rootTree = VersionTreeUtil.getVersionTree(rootTreeDsId, rootTreeVersion);
      
      VersionTree tree = VersionTreeUtil.getVersionTree(dsId, version);
      Node treeNode = rootTree.findNode(path);
      if(path.equals("//")){
        treeNode = tree.getRoot();
      }
      
      Node rootTreeNode = rootTree.findNode(treeNode.getPath());
      
      String userClickNodePath = rootTreeNode.getPath();
      
      UIversionTreeUtil.recovery(rootTreeNode,abDir,nid,userClickNodePath,true);
      
      RecoveryBean recovery = new RecoveryBean();
      recovery.setDsId(dsId);
      recovery.setPath(view.getRoot() + path);
      recovery.setVersion(version);
      recovery.setRecoveryPath(abDir);
      recovery.setNid(nid);
      recovery.setUserClickNodePath(userClickNodePath);

      LOG.info("RecoveryBean - {}", recovery);
      DbUtil.initConnection();
      DbUtil.initDatabase();
      DbUtil.addRecoveryTask(recovery);
      
    }else{
      RecoveryBean recovery = new RecoveryBean();
      recovery.setDsId(dsId);
      recovery.setPath(view.getRoot() + path);
      recovery.setVersion(version);
      recovery.setRecoveryPath(abDir+view.getName());
      recovery.setNid(nid);

      LOG.info("RecoveryBean - {}", recovery);
      DbUtil.initConnection();
      DbUtil.initDatabase();
      DbUtil.addRecoveryTask(recovery);
    }
    
//    if(view.getDsType().equals(Constants.DS_TYPE_TREE)){
//      version = view.getCurrentVersionMajor() + "." + view.getCurrentVersionMinor();
//      VersionTree tree = VersionTreeUtil.getVersionTree(dsId, version);
//      Node node = tree.findNode(path);
//      UIversionTreeUtil.recovery(node,abDir+view.getName(),nid,false);
//      return json.toString();
//    }
    return json.toString();
    

  }

  /**
   * @author zhangjf
   * @Description: 手动备份
   * @param @param dsId 数据源id
   * @param @param dsSecurityRank 数据源安全等级
   * @param @param dynamicCode 验证码
   * @param @return
   * @return String
   * @date 2015年10月29日上午8:47:08
   *
   * @修改人 zhangjf
   * @修改日期
   */
  @RequestMapping(value = "/backup", method = RequestMethod.GET)
  public String backup(String dsId, String dsSecurityRank, String dynamicCode) {

    JSONObject json = new JSONObject();
    
    //需求该了，备份不需要验证权限了。
//    JSONObject check =
//        DatasourceSecurityRankUtil.check(Integer.valueOf(dsSecurityRank), dynamicCode, session);
//    if (!check.getString("code").equals("200")) {
//      return check.toString();
//    }
    
    String rsStr = ApiUtil.getDataSourceByDsId(dsId);
    JSONObject rsJson = JSONObject.parseObject(rsStr);
    JSONObject dsJson = rsJson.getJSONObject("obj");
    int status = dsJson.getIntValue("status");
    int dsStatus = dsJson.getIntValue("dsStatus");
    if(dsStatus == Constants.DS_STATUS_NOUSE){
      json.put("code", "500");
      json.put("message", "该数据源已停用，请先启用该数据源再进行备份");
      return json.toString();
    }
    if(status==Constants.DS_RUN_STATUS_RUNNING){
      json.put("code", "500");
      json.put("message", "该数据源已在备份中!");
      return json.toString();
    }

    BackupBean bean = new BackupBean();
    bean.setDsId(dsId);
    bean.setStatus(0);
    try {
      DbUtil.initConnection();
      DbUtil.initDatabase();
      DbUtil.deleteBackupTaskByDsid(dsId);
      DbUtil.addBackupTask(bean);
      json.put("code", "200");
    } catch (SQLException e) {
      e.printStackTrace();
      json.put("code", "sqlite 404");
    }

    return json.toString();
  }
}
